package com.slkj.shilixiaoyuanapp.ui.parent.tool.bodyartspecialty;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.slkj.shilixiaoyuanapp.BuildConfig;
import com.slkj.shilixiaoyuanapp.R;
import com.slkj.shilixiaoyuanapp.base.ActivityInfo;
import com.slkj.shilixiaoyuanapp.base.BaseActivity;
import com.slkj.shilixiaoyuanapp.data.LeaveTypeData;
import com.slkj.shilixiaoyuanapp.data.UserRequest;
import com.slkj.shilixiaoyuanapp.entity.BasePickerTypeEntity;
import com.slkj.shilixiaoyuanapp.entity.PeopleEntity;
import com.slkj.shilixiaoyuanapp.entity.UserEntity;
import com.slkj.shilixiaoyuanapp.entity.code.ToolCode;
import com.slkj.shilixiaoyuanapp.entity.code.UiCode;
import com.slkj.shilixiaoyuanapp.entity.parent.BodyartspecialtyEntity;
import com.slkj.shilixiaoyuanapp.net.CommonResult;
import com.slkj.shilixiaoyuanapp.net.HttpHeper;
import com.slkj.shilixiaoyuanapp.net.callback.BaseFunctionCallBack;
import com.slkj.shilixiaoyuanapp.net.callback.CommonCallBack;
import com.slkj.shilixiaoyuanapp.ui.common.ChoseAuditorActivity__JumpCenter;
import com.slkj.shilixiaoyuanapp.ui.common.ChosePeopleActivity__JumpCenter;
import com.slkj.shilixiaoyuanapp.ui.common.adapter.ChosePicAdapter;
import com.slkj.shilixiaoyuanapp.ui.parent.tool.common.CommonToolHistoryActivity__JumpCenter;
import com.slkj.shilixiaoyuanapp.util.StringUtils;
import com.slkj.shilixiaoyuanapp.util.TimeUtils;
import com.slkj.shilixiaoyuanapp.util.UpdataFileUtil;
import com.slkj.shilixiaoyuanapp.util.picture.FileUtils;
import com.slkj.shilixiaoyuanapp.util.picture.TakePictureUtils;
import com.slkj.shilixiaoyuanapp.view.DialogProvider;
import com.slkj.shilixiaoyuanapp.view.PickerViewProvider;
import com.slkj.shilixiaoyuanapp.view.dialog.LoadSuccessAndFailDialog;
import com.tkk.api.RxEventProcessor;
import com.tkk.api.annotation.Recipient;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.ObservableSource;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.RuntimePermissions;

import static com.slkj.shilixiaoyuanapp.entity.code.RxEventProcessorTag.CHOSE_SPR_FINSH;
import static com.slkj.shilixiaoyuanapp.entity.code.UiCode.CHOSE_PIC_MAX_SIZW;
import static com.slkj.shilixiaoyuanapp.entity.code.UiCode.CHOSE_PIC_SPAN_COUNT;
import static com.slkj.shilixiaoyuanapp.entity.code.UiCode.NO_CHOSE;

@RuntimePermissions
@ActivityInfo(layout = R.layout.activity_bodyartspecialty, title = "体艺特长", rightHint = "历史记录")
public class BodyartspecialtyActivity extends BaseActivity {
    //获奖级别id
    private int qjTypeId = NO_CHOSE;
    //班级班级
    private int classId = NO_CHOSE;
    //学生id
    private int studentId = NO_CHOSE;
    //获奖等级id
    private int winlevelId=NO_CHOSE;
    //获奖类别id
    private int wintypeId=NO_CHOSE;
    //
    private int wintype;

    @BindView(R.id.tv_win_level)
    TextView tv_win_level;
    @BindView(R.id.tv_winning_time1)
    TextView tv_winning_time1;
    String time;
    @BindView(R.id.tv_student_name)
    TextView tv_student_name;
    @BindView(R.id.tv_winning_type1)
    TextView tv_winning_type1;
    List<Integer> sqrIds = new ArrayList<>();
    public static final String tag = "LeaveActivity";
    @BindView(R.id.tv_spr)
    TextView tvSpr;
    @BindView(R.id.edit_winning_name)
    EditText edit_winning_name;
    @BindView(R.id.edit_winning_level)
    TextView edit_winning_level;
    @BindView(R.id.recyc_pic)
    RecyclerView recyc_pic;
    @BindView(R.id.edit_organizers)
    EditText editOrganizers;
    private ArrayList<BodyartspecialtyEntity.AuditorEntity> peopleEntities = new ArrayList<>();
    private ArrayList<String> picPaths = new ArrayList<>();
    public TakePictureUtils takePictureUtils;
    ChosePicAdapter adapter;
    //缓存数据
    BodyartspecialtyEntity cacheData;

    @Override
    protected void init() {
        for (int i=0;i<UserRequest.getInstance().getUser().getStudents().size();i++){
            if (UserRequest.getInstance().getUser().getStudents().get(i).getIsSelect()==1){
                studentId=UserRequest.getInstance().getUser().getStudents().get(i).getId();
                classId=UserRequest.getInstance().getUser().getStudents().get(i).getClassId();
                tv_student_name.setText(UserRequest.getInstance().getUser().getStudents().get(i).getName());
            }
        }
//        if (UserRequest.getInstance().getUser().getStudents().size()!=0) {
//            tv_student_name.setText(UserRequest.getInstance().getUser().getStudents().get(0).getName());
//        }
        RxEventProcessor.get().bind(this);
        getData();
        recyc_pic.setLayoutManager(new GridLayoutManager(this, CHOSE_PIC_SPAN_COUNT));
        adapter = new ChosePicAdapter(picPaths, this);
        recyc_pic.setAdapter(adapter);
        takePictureUtils = TakePictureUtils.Builder.from(this).isCompressor(false).isTailor(false).creat();
        takePictureUtils.setTakeCallBacklistener(new TakePictureUtils.TakePictureListener() {
            @Override
            public void successful(File outFile) {
                picPaths.add(outFile.getPath());
                adapter.notifyItemInserted(picPaths.size());
            }

            @Override
            public void failed(int errorCode, List<String> deniedPermissions) {
            }
        });
    }

    private void getData() {
        HttpHeper.get().parentService().getBodyartspecialty().compose(getThread())
                .compose(bindToLifecycle())
                .subscribe(new CommonCallBack<BodyartspecialtyEntity>(true, this) {
                    @Override
                    public void onCallBackSuccess(BodyartspecialtyEntity data) {
                        cacheData = data;
                    }
                });
    }

    @Override
    protected void onRightTitleClick() {
        CommonToolHistoryActivity__JumpCenter.builder(this)
                .setNetToolType(10)
                .setToolType(ToolCode.P_TOOL_TYTC)
                .create().go();
    }

//    /**
//     * 选择学生
//     */
//    @OnClick(R.id.layout_chose_student)
//    public void onLayoutChooseStudent() {
//        List<UserEntity.StudentEntity> students = UserRequest.getInstance().getUser().getStudents();
//        PickerViewProvider.getCommonPicker(this, students, new OnOptionsSelectListener() {
//            @Override
//            public void onOptionsSelect(int options1, int options2, int options3, View v) {
//                tv_student_name.setText(students.get(options1).getName());
//                studentId = students.get(options1).getId();
//                classId  = students.get(options1).getClassId();
//            }
//        }).show();
//    }

    /**
     * 奖项级别
     */
    @OnClick(R.id.layout_chose_win_level)
    public void onLayoutChooseWinLevel() {
        PickerViewProvider.getCommonPicker(this, cacheData.getAwardLevel(), new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                tv_win_level.setText(cacheData.getAwardLevel().get(options1).getAName());
                qjTypeId = cacheData.getAwardLevel().get(options1).getAId();
            }
        }).show();
    }

    /**
     * 奖项等级
     */
    @OnClick(R.id.layout_choose_winlevel)
    public void onLayoutChooseWinLevel1() {
        PickerViewProvider.getCommonPicker(this, cacheData.getLevel(), new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                edit_winning_level.setText(cacheData.getLevel().get(options1).getLName());
                winlevelId = cacheData.getLevel().get(options1).getLId();
            }
        }).show();
    }

    /**
     * 选择时间
     */
    @OnClick(R.id.layout_winning_time)
    public void onLayoutChooseWinTime() {
        PickerViewProvider.getDayTimePicker(this, (date, v) -> {
            time = TimeUtils.dateToStr(date);
            tv_winning_time1.setText(time);
        }).show();
    }

    /**
     * 获奖类别
     */
    @OnClick(R.id.layout_winning_type)
    public void onLayoutChooseWinType() {
        List<BasePickerTypeEntity> typeEntityList1 = LeaveTypeData.getInstance().getParentWinningType1();
        List<List<BasePickerTypeEntity>> typeEntityList2 = new ArrayList<>();
        List<BasePickerTypeEntity> list1=new ArrayList<>();
        List<BasePickerTypeEntity> list2=new ArrayList<>();
        typeEntityList2.add(list1);
        typeEntityList2.add(list2);
        for (int i=0;i<cacheData.getArt().size();i++){
            typeEntityList2.get(0).add(new BasePickerTypeEntity(cacheData.getArt().get(i).getName()));
        }
        for (int i=0;i<cacheData.getSport().size();i++){
            typeEntityList2.get(1).add(new BasePickerTypeEntity(cacheData.getSport().get(i).getName()));
        }
        PickerViewProvider.getWinTypePicker(this, typeEntityList1, typeEntityList2, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                tv_winning_type1.setText(typeEntityList1.get(options1).getName() + " " + typeEntityList2.get(options1).get(options2).getName());
                if (options1==0){
                    wintypeId=cacheData.getArt().get(options2).getId();
                    wintype=1;
                }else {
                    wintypeId=cacheData.getSport().get(options2).getId();
                    wintype=2;
                }
            }
        }).show();
    }

    @OnClick(R.id.tv_up)
    void commit() {
        if (studentId == NO_CHOSE) {
            showToast("请选择学生");
            return;
        }
        String organizers = editOrganizers.getText().toString();
        if (TextUtils.isEmpty(organizers)){
            showToast("请填写主办单位");
            return;
        }
        String winName = edit_winning_name.getText().toString();
        if (TextUtils.isEmpty(winName)) {
            showToast("请填写奖项名称");
            return;
        }
        String winLevel = edit_winning_level.getText().toString();
        if (winlevelId==NO_CHOSE) {
            showToast("请填写奖项等级");
            return;
        }
        String winLevel1 = tv_win_level.getText().toString();
        if (qjTypeId==NO_CHOSE) {
            showToast("请选择奖项级别");
            return;
        }
        if (TextUtils.isEmpty(time)) {
            showToast("请选择获奖时间");
            return;
        }
        String winType = tv_winning_type1.getText().toString();
        if (wintypeId==NO_CHOSE) {
            showToast("请选择获奖类别");
            return;
        }
        if (sqrIds.size() == 0) {
            showToast("请选择审批人");
            return;
        }
        UpdataFileUtil.UpImgObservable("award", picPaths)
                .flatMap(new BaseFunctionCallBack<List<String>, String>() {
                    @Override
                    public ObservableSource<CommonResult<String>> back(List<String> result) {
                        String img = StringUtils.listToString(result);
//                        int studentId = UserRequest.getInstance().getUser().getStudents().get(0).getId();
//                        String name = edit_winning_name.getText().toString();
//                        String time = tv_winning_time1.getText().toString();
                        String spr = tvSpr.getText().toString();
                        return HttpHeper.get().parentService().addBodyartspecialty(studentId, classId, organizers, winName, winlevelId, qjTypeId, time, wintype, wintypeId, sqrIds.toString(), img);
                    }
                })
                .compose(getThread())
                .compose(bindToLifecycle())
                .subscribe(new CommonCallBack<String>(true, this) {
                    @Override
                    public void onCallBackSuccess(String data) {
                        LoadSuccessAndFailDialog.showSuccess(BodyartspecialtyActivity.this, data);
                        clearContent();
                    }
                });
    }

    @Recipient(tag = tag + CHOSE_SPR_FINSH)
    void onChoseObjFinsh(int code, String info, List<BodyartspecialtyEntity.AuditorEntity> peopleEntityList, List<Integer> checkIds) {
        tvSpr.setText(checkIds.size() == 0 ? "" : info);
        sqrIds.clear();
        sqrIds.addAll(checkIds);
        peopleEntities.clear();
        peopleEntities.addAll(peopleEntityList);
    }

    @OnClick(R.id.layout_chose_pic)
    void chosePic() {
        if (picPaths.size() == CHOSE_PIC_MAX_SIZW) {
            showToast("最多添加" + CHOSE_PIC_MAX_SIZW + "张图片");
            return;
        }
        DialogProvider.getPhotoDialog(this, new DialogProvider.TakePicTypeListener() {
            @Override
            public void takePhoto() {
                takePictureUtils.getByCarema();
            }

            @Override
            public void chosePhoto() {
                BodyartspecialtyActivityPermissionsDispatcher.onAgreePermissionWithPermissionCheck(BodyartspecialtyActivity.this);
            }
        });

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        takePictureUtils.attachToActivityForResult(requestCode, resultCode, data);
        if (requestCode == UiCode.CHOSE_PIC_CODE && resultCode == RESULT_OK) {
            List<Uri> mSelected = Matisse.obtainResult(data);
            for (int i = 0; i < mSelected.size(); i++) {
                String filePath = FileUtils.getPathByUri(this, mSelected.get(i));
                picPaths.add(filePath);
            }
            adapter.notifyItemRangeInserted(picPaths.size(), mSelected.size());
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        takePictureUtils.onRequestPermissionsResult(requestCode, permissions, grantResults);
        BodyartspecialtyActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @NeedsPermission({Manifest.permission.CAMERA})
    void onAgreePermission() {
        Matisse.from(this)
                .choose(MimeType.ofImage())
                .countable(true)
                .maxSelectable(CHOSE_PIC_MAX_SIZW - picPaths.size())
                .captureStrategy(new CaptureStrategy(true, BuildConfig.APPLICATION_ID + ".fileprovider"))
                .imageEngine(new GlideEngine())
                .forResult(UiCode.CHOSE_PIC_CODE);
    }

    @OnPermissionDenied({Manifest.permission.CAMERA})
    void onDeniedPermission() {
        showToast("读取照片权限获取失败");
    }

    @OnClick(R.id.layout_chose_spr)
    public void onLayoutChoseSprClicked() {
        if (peopleEntities.size() == 0) {
            HttpHeper.get().toolService().getCommonSpr(6)
                    .compose(bindToLifecycle())
                    .compose(getThread())
                    .subscribe(new CommonCallBack<ArrayList<PeopleEntity>>(true, this) {
                        @Override
                        public void onCallBackSuccess(ArrayList<PeopleEntity> data) {
                            peopleEntities.addAll(cacheData.getAuditor());
                            ChoseAuditorActivity__JumpCenter.builder(BodyartspecialtyActivity.this).setTag(tag).setData(peopleEntities).create().go();
                        }
                    });
        } else {
            ChoseAuditorActivity__JumpCenter.builder(BodyartspecialtyActivity.this).setTag(tag).setData(peopleEntities).create().go();

        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        RxEventProcessor.get().unBind(this);
    }


}
